package com.dbmanager;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DbManager {
	static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
	static final String DB_URL = "jdbc:mysql://localhost/test";

	static final String USER = "root";
	static final String PASS = "root";
	Connection conn;
	Statement stmt;
	ResultSet rs;

	public Connection getConnection() throws ClassNotFoundException,
			SQLException {
		Class.forName(JDBC_DRIVER);

		this.conn = DriverManager.getConnection(DB_URL, USER, PASS);
		return this.conn;
	}

	public boolean insert(String sql) {
		try {
			this.conn = getConnection();
			this.stmt = this.conn.createStatement();
			this.stmt.executeUpdate(sql);
			
			return true;
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		} catch (SQLException e) {

			e.printStackTrace();
			return false;
		}finally{
			try {
				freeResource();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}
	public boolean select(String sql) {
		byte count = 0;
		try {
			this.conn = getConnection();
			this.stmt = this.conn.createStatement();
			rs = this.stmt.executeQuery(sql);
			
			while (rs.next()) {
				count++;
				System.out.println(rs.getString(1));
			}
			if(count == 1)
				return true;
			else
				return false;
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		} catch (SQLException e) {

			e.printStackTrace();
			return false;
		}finally{
			try {
				freeResource();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}
	public void freeResource() throws SQLException {
		this.stmt.close();
		this.conn.close();

	}
	
}
